//var username = sessionStorage.getItem("username");
var sum;
var counts = '';
var pageThis = 0;
var pagecount = 4;
var index = 0;

/*var getTeacherResourceUrl = baseUrl + "/common/famousTeacher/getTeacherResource";*/

var teacherId = sessionStorage.getItem("myselfTeacherId");

function getMyInfo() {
    var data = {
        username: myUsername
    };
    AjaxSubmit("GET", data, basePath + "/teacher/myInfo", getMyInfo_fun);

    $("#changeHeadPic").change(function () {
        var files = this.files;
        $.each(files, function (i, e) {
            var fileReader = new FileReader();
            fileReader.readAsDataURL(e);
            e.mark = Math.random();
            fileReader.onload = function () {
                $("#showHeadPic").attr("src", this.result);
            }
        })
    })
}

// 修改头像
function changeHeadPic() {
    var formData = new FormData();
    formData.append("file", $("#changeHeadPic").val());
    formData.append("id", teacherId);

    $.ajax({
        url: basePath + "/common/famousTeacher/changeHeadPic",
        type: 'POST',
        cache: false,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        beforeSend: function () {
            uploading = false;
        },
        success: function (data) {
            if (data === "SUCCESS") {
                alert("上传成功");
            } else {
                alert("上传失败，请重试！");
            }
            uploading = true;
        },
        error: function (err) {
            // alert(err);
            alert("服务器异常！");
            uploading = true;
        }
    });
}

// 个人信息
function getMyInfo_fun(res) {
    $("#headPic").attr("src", res.pic);
    $("#showHeadPic").attr("src", res.pic);
    var positional = '教授';
    if (res.positional == 'ASSOCIATE_PROFESSOR')
        positional = '副教授';
    else if (res.positional == 'LECTURER')
        positional = '讲师';
    else if (res.positional == 'INSTRUCTOR')
        positional = '辅导员';
    $(".name").html(res.teacherName);
    $(".xueyuan").html(res.schoolName + ',' + positional);
    getBrief(res.brief);
    getAcademicPapers(res.id);
    // 获取学术著作
    getTeacherResource(teacherId, 1);
    // 获取教学成果
    getTeacherResource(teacherId, 2);
    // 获取学术论文
    getTeacherResource(teacherId, 3);
    // 获取我的视频
    searchResource(teacherId);
    // 获取网络资源
    getWangLuoZiYuan();
}

// 获取教师资源
function getTeacherResource(teacherId, type) {
    var data = {
        teacherId: teacherId,
        teacherResourceTypeId: type,
        page: index,
        size: pagecount
    }
    commonAjax(baseUrl + "/common/famousTeacher/getTeacherResource", data, "getTeacherResourceResult", "GET", type);
}

function getTeacherResourceResult(res, type) {
    var resultData = res.obj.content;

    var teacherResourceHtml = "";

    if (type == 1) { // 学术著作
        for (var i = 0; i < resultData.length; i++) {
            teacherResourceHtml += "<li data-id='" + resultData[i].id + "'><span class='span-edit'>" + resultData[i].title + "</span></li>";
        }

        $("#teacherResourceXueShuZhuZuo").html(teacherResourceHtml);
    } else if (type == 2) { // 教学成果
        for (var i = 0; i < resultData.length; i++) {
            teacherResourceHtml += "<li data-id='" + resultData[i].id + "'><span class='span-edit'>" + resultData[i].title + "</span></li>";
        }

        $("#teacherResourceJiaoXueChengGuo").html(teacherResourceHtml);
    } else if (type == 3) { // 学术论文
        /*for (var i = 0; i < resultData.length; i++) {
         teacherResourceHtml += "<li class='clearfix'>";
         teacherResourceHtml += "<div class='lunwen'>";
         teacherResourceHtml += "<p class='bold'>" + resultData[i].title + "</p>";
         teacherResourceHtml += "<p>" + teacherName + "</p>";
         teacherResourceHtml += "<p>" + resultData[i].text + "</p>";
         teacherResourceHtml += "<p class='important'>关键字：" + resultData[i].keyWord + "</p>";
         teacherResourceHtml += "</div>";
         teacherResourceHtml += "</li>";
         }*/
        sum = res.obj.totalElements;
        counts = sum / pagecount;
        if (resultData.length != 0) {
            $("#xueshuPage").css("display", "block");
            if (sum % pagecount == 0) {
                counts = parseInt(sum / pagecount);
            }
            else {
                counts = parseInt(sum / pagecount) + 1;
            }
            $("#xueshuPage").paging({
                pageNo: pageThis,
                totalPage: counts,
                totalSize: sum,
                callback: function (num) {
                    console.log(num);
                    index = num - 1;
                    getTeacherResource(teacherId, type);
                    pageThis = num;
                }
            });
            $("#teacherResourceXueShuLunWen").empty();
            $.each(resultData, function (i, resultDataOne) {
                teacherResourceHtml += "<li class='clearfix' data-id='" + resultDataOne.id + "'>";
                teacherResourceHtml += "<div class='lunwen'>";
                teacherResourceHtml += "<p class='bold'>" + resultDataOne.title + "</p>";
                /*teacherResourceHtml += "<p>" + resultData.teacherName + "</p>";*/
                teacherResourceHtml += "<p>" + resultDataOne.text + "</p>";
                teacherResourceHtml += "<p class='important'>关键字：" + resultDataOne.keyWord + "</p>";
                teacherResourceHtml += "</div>";
                teacherResourceHtml += "</li>";
            });

            $("#teacherResourceXueShuLunWen").append(teacherResourceHtml);


        }
        else {
            /*   $("#xueshuPage").css("display","none");
             $("#teacherResourceXueShuLunWen").empty();
             $(".warnDiv3").remove();
             var html1 = $('<div class="text-center warnDiv3" style="width: 100%;margin: 73px 0px;font-size: 14px" >无信息!</div>');
             $(".bigNew").after(html1)*/
        }
    }
}

// 获取我的视频
function searchResource(teacherId) {
    var data = {
        page: 0,
        size: 10,
        userId: teacherId
    }

    commonAjax(baseUrl + "/common/famousTeacher/searchResource", data, "searchResourceResult", "GET");
}

function searchResourceResult(res) {
    var resultData = res.obj.content;
    console.log(resultData);
    /*var resourceWoDeShiPinHtml = "";

     for (var i = 0; i < resultData.length; i++) {
     resourceWoDeShiPinHtml += "<div class='imgBoxList'>";
     resourceWoDeShiPinHtml += "<img src='" + resultData[i].pic + "' alt=''>";
     resourceWoDeShiPinHtml += "<p>" + resultData[i].title + "</p>";
     resourceWoDeShiPinHtml += "<p class='time'>" + resultData[i].whereFrom + "</p>";
     resourceWoDeShiPinHtml += "</div>";
     }

     $("#resourceWoDeShiPin").html(resourceWoDeShiPinHtml);*/
    var resourceWoDeShiPinHtml = "";
    sum = res.obj.totalElements;
    counts = sum / pagecount;
    if (resultData.length != 0) {
        $("#videoPage").css("display", "block");
        if (sum % pagecount == 0) {
            counts = parseInt(sum / pagecount);
        }
        else {
            counts = parseInt(sum / pagecount) + 1;
        }
        $("#videoPage").paging({
            pageNo: pageThis,
            totalPage: counts,
            totalSize: sum,
            callback: function (num) {
                console.log(num);
                index = num - 1;
                searchResource(teacherId)
                pageThis = num;
            }
        });
        $("#resourceWoDeShiPin").empty();
        $.each(resultData, function (i, resultDataOne) {
            resourceWoDeShiPinHtml += "<div class='imgBoxList' data-id='" + resultDataOne.id + "'>";
            resourceWoDeShiPinHtml += "<img src='" + resultDataOne.pic + "' alt=''>";
            // resourceWoDeShiPinHtml += "<img src='../img/mks.jpg' alt=''>";
            resourceWoDeShiPinHtml += "<p>" + resultDataOne.title + "</p>";
            resourceWoDeShiPinHtml += "<p class='time'>" + toHourMinute(resultDataOne.videoTime) + "</p>";
            resourceWoDeShiPinHtml += "</div>";
        });

        $("#resourceWoDeShiPin").html(resourceWoDeShiPinHtml);


    }
    else {
        $("#resourceWoDeShiPin").empty();
        $("#videoPage").css("display", "none");
        /*   $("#videoPage").css("display","none");
         $("#resourceWoDeShiPin").empty();
         $(".warnDiv3").remove();
         var html1 = $('<div class="text-center warnDiv3" style="width: 100%;margin: 73px 0px;font-size: 14px" >无信息!</div>');
         $(".bigNew").after(html1)*/
    }

}
//删除我的视频
function wdspdelete() {
    $("#resourceWoDeShiPin").find("input[type=checkbox]").each(function () {
        if ($(this).prop('checked') == true)
            var id = $(this).parent().attr("data-id");
        console.log(id);
        if (id !== null && id != undefined) {
            var data = '{"resourceId":' + id + '}';
            $.ajax({
                type: 'POST',
                url: basePath + '/common/famousTeacher/deleteResource',
                data: JSON.parse(data),
                dataType: "json",
                success: function () {
                    alert("删除成功");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //alert("出现异常");
                }
            });
        }
    })
    location.reload();
}

//获取网络资源
function getWangLuoZiYuan() {
    var data = {
        teacherId: teacherId,
        teacherResourceTypeId: 4,
        page: 0,
        size: 5
    };
    $.ajax({
        type: 'GET',
        url: basePath + "/common/famousTeacher/getTeacherResource",
        data: data,
        dataType: "json",
        success: function (res) {
            console.log(res);
            sum = res.obj.totalElements;
            resultData = res.obj.content;
            counts = sum / pagecount;
            if (resultData.length != 0) {
                var html = '';
                $(".wordlist").empty();
                $.each(resultData, function (i, resultDataOne) {
                    html += '<div class="col-md-6 border-bottom" data-id="' + resultDataOne.id + '"><img src="../img/blue.png" alt="" class="pull-left"><p class="wordname">' + resultDataOne.title + '</p> </div>';
                });

                $(".wordlist").append(html);


            }
            else {
                $(".wordlist").empty();
                /*  $(".warnDiv3").remove();
                 var html1 = $('<div class="text-center warnDiv3" style="width: 100%;margin: 73px 0px;font-size: 14px" >无信息!</div>');
                 $(".bigNew").after(html1)*/
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
            // alert(XMLHttpRequest.responseText);
        }
    });
}

//简介
function getBrief(brief) {
    // $.ajax({
    //     type: 'GET',
    //     url: basePath + "/teacher/myInfo",
    //     data: {
    //         // famousTeacherId:res
    //     },
    //     dataType: "json",
    //     success: function (msg) {
    //
    //     },
    //     error: function (XMLHttpRequest, textStatus, errorThrown) {
    //         console.log(XMLHttpRequest);
    //         // alert(XMLHttpRequest.responseText);
    //     }
    // });
    $("#berf").html(brief);
    editor.txt.html(brief);
}

//编辑简介
function saveBrief() {
    $.ajax({
        type: 'POST',
        url: basePath + "/common/famousTeacher/updateTeacherBrief",
        data: {
            brief: editor.txt.html(),
            id: teacherId
        },
        dataType: "json",
        success: function (msg) {
            location.reload();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
            // alert(XMLHttpRequest.responseText);
        }
    });
}

//学术论文
function getAcademicPapers(res) {
    $.ajax({
        type: 'GET',
        url: basePath + "/common/famousTeacher/getAcademicPapers",
        data: {
            teacherId: res
        },
        dataType: "json",
        success: function (msg) {
            console.log(msg);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
            // alert(XMLHttpRequest.responseText);
        }
    });
}
//新增视频
function addResourceVideo(btn) {
    $("#addFile").modal("toggle");
    $(".easy_upload_upbtn").show();
    var filetype = $(btn).attr("data-typeId");
    $('#easyContainer').easyUpload({
        allowFileTypes: '*',//允许上传文件类型，格式';*.doc;*.pdf'
        allowFileSize: 2000000,//允许上传文件大小(KB)
        selectText: '选择文件',//选择文件按钮文案
        multi: false,//是否允许多文件上传
        multiNum: 5,//多文件上传时允许的文件数
        showNote: false,//是否展示文件上传说明
        note: '提示：最多上传5个文件，支持格式为doc、pdf、jpg',//文件上传说明
        showPreview: false,//是否显示文件预览
        url: basePath + '/common/famousTeacher/addResource',//上传文件地址
        fileName: 'file',//文件filename配置参数
        formParam: {
            userId: parseInt(teacherId),
            username: myUsername
        },//文件filename以外的配置参数，格式：{key1:value1,key2:value2}
        timeout: 6000000,//请求超时时间
        okCode: '1000',//与后端返回数据code值一致时执行成功回调，不配置默认200
        successFunc: function (res) {
            location.reload();
        },//上传成功回调函数
        errorFunc: function (res) {

        },//上传失败回调函数
        deleteFunc: function (res) {

        }//删除文件回调函数
    })

}
//新增网络资源
function addResourceWang(btn) {
    $("#addFile").modal("toggle");
    $(".easy_upload_upbtn").show();
    var filetype = $(btn).attr("data-typeId");
    $('#easyContainer').easyUpload({
        allowFileTypes: '*',//允许上传文件类型，格式';*.doc;*.pdf'
        allowFileSize: 2000000,//允许上传文件大小(KB)
        selectText: '选择文件',//选择文件按钮文案
        multi: false,//是否允许多文件上传
        multiNum: 5,//多文件上传时允许的文件数
        showNote: false,//是否展示文件上传说明
        note: '提示：最多上传5个文件，支持格式为doc、pdf、jpg',//文件上传说明
        showPreview: false,//是否显示文件预览
        url: basePath + '/teacher/addTeacherResourceWithFile',//上传文件地址
        fileName: 'file',//文件filename配置参数
        formParam: {
            teacherResourceTypeId: 4,
            teacherId: parseInt(teacherId)
        },//文件filename以外的配置参数，格式：{key1:value1,key2:value2}
        timeout: 6000000,//请求超时时间
        okCode: '1000',//与后端返回数据code值一致时执行成功回调，不配置默认200
        successFunc: function (res) {
            location.reload();
        },//上传成功回调函数
        errorFunc: function (res) {

        },//上传失败回调函数
        deleteFunc: function (res) {

        }//删除文件回调函数
    })


}
//删除网络资源
function deleteWangluo() {
    $("#WangLuoResource").find("input[type=checkbox]").each(function () {
        if ($(this).prop('checked') == true)
            var id = $(this).parent().attr("data-id");
        console.log(id);
        if (id !== null && id != undefined) {
            var data = '{"teacherResourceId":' + id + '}';
            $.ajax({
                type: 'POST',
                url: basePath + '/teacher/deleteTeacherResource',
                data: JSON.parse(data),
                dataType: "json",
                success: function () {
                    //alert("删除成功");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //alert("出现异常");
                }
            });
        }
    })
    location.reload();
}
//新增学术学术著作
function savexxzzcg(btn) {
    var title = $("#zzcgtitle").val();
    var teacherResourceTypeId = 1;
    $.ajax({
        type: 'POST',
        url: basePath + '/teacher/addTeacherResource',
        data: {
            title: title,
            teacherResourceTypeId: teacherResourceTypeId,
            teacherId: teacherId
        },
        dataType: "json",
        success: function (res) {
            console.log(res);
            //alert("删除成功");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("出现异常");
        }
    });
    location.reload();
}

//新增教学成果
function savejxcg(btn) {
    var title = $("#jxcgtitle").val();
    var teacherResourceTypeId = 2;
    $.ajax({
        type: 'POST',
        url: basePath + '/teacher/addTeacherResource',
        data: {
            title: title,
            teacherResourceTypeId: teacherResourceTypeId,
            teacherId: teacherId
        },
        dataType: "json",
        success: function (res) {
            //alert("删除成功");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("出现异常");
        }
    });
    location.reload();
}

//新增学术论文
function savexueshu() {
    var title = $("#xueshutitle").val();
    var text = $("#xueshucontent").val();
    var keyWord = $("#keyword").val();
    var teacherResourceTypeId = 3;
    $.ajax({
        type: 'POST',
        url: basePath + '/teacher/addTeacherResource',
        data: {
            title: title,
            text: text,
            keyWord: keyWord,
            teacherResourceTypeId: teacherResourceTypeId,
            teacherId: teacherId
        },
        dataType: "json",
        success: function () {
            //alert("删除成功");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("出现异常");
        }
    });
    location.reload();
}

//批量删除学术著作
function xszzelete() {
    $("#teacherResourceXueShuZhuZuo").find("input[type=checkbox]").each(function () {
        if ($(this).prop('checked') == true)
            var id = $(this).parent().attr("data-id");
        console.log(id);
        if (id !== null && id != undefined) {
            var data = '{"teacherResourceId":' + id + '}';
            $.ajax({
                type: 'POST',
                url: basePath + '/teacher/deleteTeacherResource',
                data: JSON.parse(data),
                dataType: "json",
                success: function () {
                    //alert("删除成功");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //alert("出现异常");
                }
            });
        }
    })
    location.reload();
}

//批量删除我的视频
function wdspdelete() {
    $("#resourceWoDeShiPin").find("input[type=checkbox]").each(function () {
        if ($(this).prop('checked') == true)
            var id = $(this).parent().attr("data-id");
        console.log(id);
        if (id !== null && id != undefined) {
            var data = '{"resourceId":' + id + '}';
            $.ajax({
                type: 'POST',
                url: basePath + '/teacher/deleteResource',
                data: JSON.parse(data),
                dataType: "json",
                success: function () {
                    //alert("删除成功");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //alert("出现异常");
                }
            });
        }
    })
    location.reload();
}

//批量删除教学成果
function jxcgdelete() {
    $("#teacherResourceJiaoXueChengGuo").find("input[type=checkbox]").each(function () {
        console.log($(this))
        if ($(this).prop('checked') == true)
            var id = $(this).parent().attr("data-id");
        console.log(id);
        if (id !== null && id != undefined) {
            var data = '{"teacherResourceId":' + id + '}';
            $.ajax({
                type: 'POST',
                url: basePath + '/teacher/deleteTeacherResource',
                data: JSON.parse(data),
                dataType: "json",
                success: function (res) {
                    console.log(res)
                    //alert("删除成功");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //alert("出现异常");
                }
            });
        }
    })
    location.reload();
}

//批量删除学术论文
function xslwdelete() {
    /*if($("#teacherResourceXueShuLunWen").find("input").eq(3).checked){
     var id=$(this).parent().parent().attr("data-id");
     console.log(id);
     }*/
    $("#teacherResourceXueShuLunWen").find("input[type=checkbox]").each(function () {
        if ($(this).prop('checked') == true)
            var id = $(this).parent().parent().attr("data-id");
        console.log(id);
        if (id !== null && id != undefined) {
            var data = '{"teacherResourceId":' + id + '}';
            $.ajax({
                type: 'POST',
                url: basePath + '/teacher/deleteTeacherResource',
                data: JSON.parse(data),
                dataType: "json",
                success: function () {
                    //alert("删除成功");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    /*alert("出现异常");*/
                }
            });
        }
    })
    location.reload();
}

//编辑学术论文
function editxxlw(btn) {
    var id = $(btn).parent().attr("data-id");
    sessionStorage.setItem("teacherResourceId", id);
    $.ajax({
        type: 'GET',
        url: basePath + '/teacher/findTeacherResource',
        data: {
            teacherResourceId: id
        },
        dataType: "json",
        success: function (res) {
            $("#editxxlwtitle").val(res.title);
            $("#editxxlwtext").val(res.text);
            $("#editxxlwkeyword").val(res.keyWord);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("出现异常");
        }
    });
}

//编辑学术著作
function editsszz(btn) {
    var id = $(btn).parent().attr("data-id");
    sessionStorage.setItem("teacherResourceId", id);
    $.ajax({
        type: 'GET',
        url: basePath + '/teacher/findTeacherResource',
        data: {
            teacherResourceId: id
        },
        dataType: "json",
        success: function (res) {
            $("#editsszztitle").val(res.title);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("出现异常");
        }
    });
}

//保存学术著作编辑
function editsavesszz() {
    var id = sessionStorage.getItem("teacherResourceId");
    var title = $("#editsszztitle").val();
    $.ajax({
        type: 'POST',
        url: basePath + '/teacher/updateTeacherResource',
        data: {
        	id: id,
            title: title,
        },
        dataType: "json",
        success: function (res) {
        	console.log(res)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("出现异常");
        }
    });
  location.reload();
}

//保存学术论文编辑
function editsavexxlw() {
    var id = sessionStorage.getItem("teacherResourceId");
    var title = $("#editxxlwtitle").val();
    var text = $("#editxxlwtext").val();
    var keyWord = $("#editxxlwkeyword").val();
    $.ajax({
        type: 'POST',
        url: basePath + '/teacher/updateTeacherResource',
        data: {
        	id: id,
            title: title,
            text: text,
            keyWord: keyWord,
        },
        dataType: "json",
        success: function (res) {
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert("出现异常");
        }
    });
    location.reload();
}

// 通用ajax请求 万能类
function commonAjax(url, requestData, methodName, requestType, sendData) {
    $.ajax({
        type: requestType,
        url: url,
        data: requestData,
        beforeSend: function (XMLHttpRequest) {
        },
        success: function (result) {
            if (result != "" && result != null) {
                if (sendData == null && sendData == "") {
                    var str = JSON.stringify(result);
                    eval('(' + methodName + '(' + str + '))');
                } else {
                    var str = JSON.stringify(result);
                    var str1 = JSON.stringify(sendData);
                    eval('(' + methodName + '(' + str + ',' + str1 + '))');
                }
            } else if (result == 0) {
                var str1 = JSON.stringify(sendData);
                eval('(' + methodName + '(' + 0 + ',' + str1 + '))');
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
        },
        error: function () {
        }
    });
}